package com.wanjia.order.server.service.impl;

import com.wanjia.order.server.entity.UserOrder;
import com.wanjia.order.server.entity.UserOrderDetails;
import com.wanjia.order.server.mapper.OrderDetailsMapper;
import com.wanjia.order.server.mapper.OrderMapper;
import com.wanjia.order.server.service.OrderService;
import com.wanjia.project.commons.bo.order.OrderAddBO;
import com.wanjia.project.commons.bo.order.OrderListBO;
import com.wanjia.project.commons.bo.order.UserOrderDetailsBO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailsMapper orderDetailsMapper;
    @Override
    public List<UserOrder> orderList(OrderListBO orderListBO) {
        List<UserOrder> userOrders = orderMapper.orderList(orderListBO);
        return userOrders;
    }

    @Override
    @Transactional
    public void addOrder(OrderAddBO orderAddBO) {
        //订单编号
       String OrderCode= UUID.randomUUID().toString().substring(0, UUID.randomUUID().toString().indexOf("-"));
        UserOrder userOrder=new UserOrder();
        userOrder.setOrderCode(OrderCode);
        userOrder.setWarehouseId(orderAddBO.getWarehouseId());
        userOrder.setStart(orderAddBO.getStart());
        userOrder.setOrderTime(orderAddBO.getOrderTime());
        userOrder.setDeliveryTime(orderAddBO.getDeliveryTime());
        userOrder.setReceivingTime(new Date());
        userOrder.setUserId(orderAddBO.getUserId());
        orderMapper.insert(userOrder);
        UserOrderDetailsBO[] details = orderAddBO.getDetails();
        for (int i = 0; i < details.length; i++) {
            UserOrderDetails userOrderDetails=new UserOrderDetails();
            userOrderDetails.setCount(details[i].getOrderQuantity());
            userOrderDetails.setPrice(details[i].getPrice().multiply(new BigDecimal(details[i].getOrderQuantity())));
            userOrderDetails.setProdectDetailsId(details[i].getProdectDetailsId());
            userOrderDetails.setUserOrderId(userOrder.getUserOrderId());
            orderDetailsMapper.insert(userOrderDetails);
        }
    }

}
